<template>
    <div>
      <el-dialog
        title="新增单位"
        :visible.sync="dialogVisible"
        width="750px"
        :before-close="closeDialog"
        :close-on-click-modal="false"
        :append-to-body="true"
      >
        <el-form :model="addForm" :rules="rules" ref="refForm" label-width="80px">
          <el-collapse
            v-model="activeNames"
            @change="handleChange"
            class="el_collapse"
          >
            <el-collapse-item title="基本信息" name="1" >
              <el-form-item size="small" label="上级机构" prop="parentId">
                <TreeSearchAdd
                  style="width: 100%"
                  ref="refTreeSearchAdd"
                  @changeOrgId="changeOrgId"
                  :clearable="false"
                ></TreeSearchAdd>
              </el-form-item>
              <el-form-item size="small" label="联网单位" prop="orgName">
                <el-input
                  clearable
                  v-model.trim="addForm.orgName"
                  placeholder="请输入"
                  style="width: 100%"
                  oninput="value=value.replace(/\s*/g,'')"
                  @blur="addForm.orgName = $event.target.value"
                  maxlength="20"
                >
                </el-input>
              </el-form-item>
              <el-form-item size="small" label="地区" prop="streetCode">
                <div style="display: flex; align-items: center">
                  <el-select
                    v-model="addForm.provinceCode"
                    placeholder="省"
                    @change="changprovince"
                    style="width: 400px; margin-right: 5px"
                  >
                    <el-option
                      v-for="(item, i) in provinceList"
                      :key="i"
                      :label="item.regionName"
                      :value="item.regionCode"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="addForm.cityCode"
                    placeholder="市"
                    @change="changcity"
                    style="width: 400px; margin-right: 5px"
                  >
                    <el-option
                      v-for="(item, i) in cityList"
                      :key="i"
                      :label="item.regionName"
                      :value="item.regionCode"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="addForm.areaCode"
                    placeholder="区"
                    @change="changarea"
                    style="width: 400px; margin-right: 5px"
                  >
                    <el-option
                      v-for="(item, i) in areaList"
                      :key="i"
                      :label="item.regionName"
                      :value="item.regionCode"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="addForm.streetCode"
                    placeholder="街道"
                    @change="changestreet"
                    style="width: 400px; margin-right: 5px"
                  >
                    <el-option
                      v-for="(item, i) in streetList"
                      :key="i"
                      :label="item.regionName"
                      :value="item.regionCode"
                    >
                    </el-option>
                  </el-select>
                  <i
                    class="iconfont zuobiao"
                    style="font-size: 20px; margin-left: 10px; cursor: pointer"
                    @click="openMap"
                  ></i>
                </div>
              </el-form-item>
  
              <el-form-item size="small" label="详细地址" prop="address">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入"
                  v-model="addForm.address"
                  oninput="value=value.replace(/\s*/g,'')"
                  @blur="addForm.address = $event.target.value"
                  maxlength="30"
                  resize="none"
                  :autosize="{ minRows: 2, maxRows: 5 }"
                >
                </el-input>
              </el-form-item>
  
              <el-row>
                <el-col :span="24">
                  <el-form-item size="small" label="社区">
                    <el-select
                      v-model="addForm.communityCode"
                      clearable
                      @change="changecommunity"
                      style="width: 100%"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="(item, i) in communityList"
                        :key="i"
                        :label="item.regionName"
                        :value="item.regionCode"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12"> </el-col>
              </el-row>
  
              <el-row>
                <el-col :span="12">
                  <el-form-item size="small" label="负责人">
                    <el-input
                      clearable
                      v-model.trim="addForm.username"
                      placeholder="请输入真实姓名"
                      oninput="value=value.replace(/\s*/g,'')"
                      @blur="addForm.username = $event.target.value"
                      maxlength="20"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item size="small" label="手机号" prop="mobile">
                    <el-input
                      clearable
                      v-model.trim="addForm.mobile"
                      placeholder="请输入负责人手机号"
                      oninput="value=value.replace(/\D/g,'')"
                      @blur="addForm.mobile = $event.target.value"
                      maxlength="11"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
            <el-collapse-item
              title="更多信息"
              name="2"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item size="small" label="监管类型">
                    <el-select
                      clearable
                      v-model="addForm.flatType"
                      style="width: 100%"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in flatTypeList"
                        :label="item.name"
                        :value="item.id"
                        :key="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item size="small" label="性质">
                    <el-select
                      clearable
                      v-model="addForm.nature"
                      style="width: 100%"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in natureList"
                        :label="item.name"
                        :value="item.id"
                        :key="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item size="small" label="类别">
                    <el-select
                      clearable
                      v-model="addForm.category"
                      style="width: 100%"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in categoryList"
                        :label="item.name"
                        :value="item.id"
                        :key="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item size="small" label="监管等级">
                    <el-select
                      clearable
                      v-model="addForm.grade"
                      style="width: 100%"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in gradeList"
                        :label="item.name"
                        :value="item.id"
                        :key="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
            <!-- <el-collapse-item title="附加信息" name="3">
            </el-collapse-item> -->
          </el-collapse>
  
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item size="small" label="法人姓名">
                <el-input clearable v-model.trim="addForm.corporateName" placeholder="请输入法人姓名"
                  oninput="value=value.replace(/\s*/g,'')" @blur="addForm.corporateName = $event.target.value"
                  maxlength="20"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item size="small" label="法人身份证" prop="corporateIdCard">
                <el-input clearable v-model.trim="addForm.corporateIdCard" placeholder="请输入法人身份证"
                  oninput="value=value.replace(/\s*/g,'')" @blur="addForm.corporateIdCard = $event.target.value"
                  maxlength="18"></el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeDialog" class="cancel-button"
            >取 消</el-button
          >
          <el-button
            size="small"
            @click="submit"
            v-preventReClick="1000"
            class="confirm-button"
            >确 定</el-button
          >
        </span>
  
        <el-dialog
          width="50%"
          title="选择地区"
          :visible.sync="innerVisible"
          append-to-body
          :close-on-click-modal="false"
        >
          <div class="mapLoc" v-if="isShowMap">
            <iframe
              :src="reqUrl"
              v-if="isShowMap"
              frameborder="0"
              class="iframe"
              seamless
              scrolling="no"
            ></iframe>
          </div>
        </el-dialog>
      </el-dialog>
  
      <!-- <div class="mapLoc" v-if="isShowMap">
        <iframe
                :src="reqUrl"
                v-if="isShowMap"
                frameborder="0"
                class="iframe"
                seamless
                scrolling="no"
              ></iframe>
            </div> -->
    </div>
  </template>
  <script>
  import { reqOrgAdd, reqRegion, reqRegionLevel } from "@api/api.js";
  import mixinRules from "./mixins/rules.js";
  import { mapState } from "vuex";
  import $ from "jquery";
  import TreeSearchAdd from "@components/TreeSearchAdd.vue";
  
  export default {
    props: ["getLocationInfo", "getAddressflag", "fixedPjtInfo"],
    mixins: [mixinRules],
    components: {
      TreeSearchAdd,
    },
    data() {
      return {
        provinceList: [],
        cityList: [],
        areaList: [],
        streetList: [],
        communityList: [], //社区
        dialogVisible: false,
        innerVisible: false,
        addForm: {
          parentId:"",
          orgName: "",
          province:"",
          provinceCode:"",
          city:"",
          cityCode:"",
          area:"",
          areaCode:"",
          street:"",
          streetCode:"",
          community:"",
          communityCode:"",
          address:"",
          lng:"",
          lat:"",
          username:"",
          mobile:"",
          flatType:"",
          nature:"",
          category:"",
          homeCountry:"",
          grade:"",
          telephone:"",
          corporateName:"",
          corporateIdCard:"",
          construction:"",
          type:"4"
        },
        reqUrl:
          "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1",
        isShowMap: false,
        LocationInfo: true, //判断是否从地图选的经纬度
        activeNames: ["1", "2"],
      };
    },
    computed: {
      ...mapState(["user"]),
    },
    watch: {
      getAddressflag() {
        if (!this.dialogVisible) return;
        this.LocationInfo = true;
        this.addForm.lat = this.getLocationInfo.getLat || "";
        this.addForm.lng = this.getLocationInfo.getLng || "";
        // 先清空
        this.addForm.province = "";
        this.addForm.provinceCode = "";
        this.addForm.city = "";
        this.addForm.cityCode = "";
        this.addForm.area = "";
        this.addForm.areaCode = "";
        this.addForm.street = "";
        this.addForm.streetCode = "";
        this.addForm.community = "";
        this.addForm.communityCode = "";
  
        this.addForm.province = this.getLocationInfo.province;
        this.addForm.city = this.getLocationInfo.city;
        this.addForm.area = this.getLocationInfo.area;
        this.addForm.street = this.getLocationInfo.street;
        this.addForm.address =
          this.getLocationInfo.address == "我的位置"
            ? ""
            : this.getLocationInfo.address;
        // this.isShowMap = false;
        this.innerVisible = false;
        this.getRegion();
      },
      "addForm.address"(e) {
        if (this.LocationInfo) return;
        this.addrHand();
      },
      "addForm.areaCode"(e) {
        if (this.LocationInfo) return;
        this.addrHand();
      },
      dialogVisible(e) {
      if (e) {
        this.addForm.parentId = this.fixedPjtInfo.orgId;
        // console.log(this.fixedPjtInfo,'fixedPjtInfo');
        this.$nextTick(() => {
          if (this.fixedPjtInfo.type != 4) {
            this.$refs.refTreeSearchAdd.getDataList(this.fixedPjtInfo.orgId);//机构列表
            this.$refs.refTreeSearchAdd.getValue(this.fixedPjtInfo.orgId);//机构赋值
          } else {
            this.addInfo.orgId = this.fixedPjtInfo.orgId//单位赋值
            this.unitflag=true;
            this.$refs.refTreeSearchAdd.getDataList(this.fixedPjtInfo.parentId);//机构列表
            this.$refs.refTreeSearchAdd.getValue(this.fixedPjtInfo.parentId);//机构赋值
          }
        });
      }
    },
      // getLocationInfo: {
      //   handler(val) {
      //     this.addForm.lat = val.getLat;
      //     this.addForm.lng = val.getLng;
      //     this.addForm.province = val.province;
      //     this.addForm.city = val.city;
      //     this.addForm.area = val.area;
      //     this.addForm.street = val.street;
      //     this.addForm.address = val.address == "我的位置" ? "" : val.address;
      //     // this.isShowMap = false;
      //     this.innerVisible = false;
      //     this.getRegion();
      //   },
      //   deep: true,
      // },
    },
    methods: {
      handleChange(val) {
        // console.log(val);
      },
      changeOrgId(instanceId) {
        // console.log(instanceId,'instanceId');
        this.addForm.parentId = instanceId.id;
      },
      getLongitudeLatitude() {
        // var geolocation = new BMap.Geolocation();
        //   geolocation.getCurrentPosition(function (r) {
        //     console.log(r.latitude);
        //     console.log(r.longitude);
        //     })
        //     return;
        // var location_lon = "";
        // var location_lat = ""; // 经度,纬度
        // if (navigator.geolocation) {
        //   navigator.geolocation.getCurrentPosition(function(position) {
        //     console.log(position);
        //     location_lon = position.coords.longitude;
        //     location_lat = position.coords.latitude;
        //     // console.log(location_lon, location_lat, "获取定位");
        //     this.reqUrl=`https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1&coord=${location_lon},${location_lat}`
        //   });
        // }
      },
      // 查询省级行政组织
      async RegionList() {
        const res = await reqRegion();
        this.provinceList = res.data.rows;
      },
      onChangeTYpe(e) {
        console.log(this.addForm.parentId, "onChangeTYpe");
      },
      // 根据省查询市
      async changprovince(val) {
        this.LocationInfo = false;
        this.addForm.address = "";
        this.cityList = [];
        this.addForm.city = "";
        this.addForm.cityCode = "";
        this.areaList = [];
        this.addForm.area = "";
        this.addForm.areaCode = "";
        this.streetList = [];
        this.addForm.street = "";
        this.addForm.streetCode = "";
        this.communityList = [];
        this.addForm.community = "";
        this.addForm.communityCode = "";
        const res = await reqRegionLevel(val);
        this.cityList = res.data.rows;
        this.provinceList.forEach((item) => {
          if (item.regionCode == val) {
            this.addForm.province = item.regionName;
            return;
          }
        });
      },
      // 根据市查询区
      async changcity(val) {
        this.LocationInfo = false;
        this.addForm.address = "";
        this.areaList = [];
        this.addForm.area = "";
        this.addForm.areaCode = "";
        this.streetList = [];
        this.addForm.street = "";
        this.addForm.streetCode = "";
        this.communityList = [];
        this.addForm.community = "";
        this.addForm.communityCode = "";
        const res = await reqRegionLevel(val);
        this.areaList = res.data.rows;
        this.cityList.forEach((item) => {
          if (item.regionCode == val) {
            this.addForm.city = item.regionName;
            return;
          }
        });
      },
      // 根据区查询街道
      async changarea(val) {
        this.LocationInfo = false;
        this.addForm.address = "";
        this.streetList = [];
        this.addForm.street = "";
        this.addForm.streetCode = "";
        this.communityList = [];
        this.addForm.community = "";
        this.addForm.communityCode = "";
        const res = await reqRegionLevel(val);
        this.streetList = res.data.rows;
        this.areaList.forEach((item) => {
          if (item.regionCode == val) {
            this.addForm.area = item.regionName;
            return;
          }
        });
      },
      // 街道名字赋值
      async changestreet(val) {
        this.communityList = [];
        this.addForm.community = "";
        this.addForm.communityCode = "";
        const res = await reqRegionLevel(val);
        this.communityList = res.data.rows;
        this.streetList.forEach((item) => {
          if (item.regionCode == val) {
            this.addForm.street = item.regionName;
            return;
          }
        });
      },
      // 社区名称赋值
      changecommunity(val) {
        this.communityList.forEach((item) => {
          if (item.regionCode == val) {
            this.addForm.community = item.regionName;
            return;
          }
        });
      },
      // 省市区获取
      async openMap() {
        // await  this.getLongitudeLatitude();
        this.isShowMap = true;
        this.innerVisible = true;
      },
      // 查询省级行政组织
      async getRegion() {
        const res = await reqRegion();
        // console.log(res);
        res.data.rows.forEach((item) => {
          if (item.regionName == this.addForm.province) {
            this.addForm.provinceCode = item.regionCode; //省行政码
            return;
          }
        });
        this.getRegionLevel();
      },
      // 查询省级下行政组织
      async getRegionLevel() {
        if (this.addForm.provinceCode == "") return;
        const res = await reqRegionLevel(this.addForm.provinceCode);
        this.cityList = res.data.rows;
        res.data.rows.forEach((item) => {
          if (item.regionName == this.addForm.city) {
            this.addForm.cityCode = item.regionCode; //市行政码
            return;
          }
        });
        // 特殊市辖区查不到  默认选择第一个
        if (this.addForm.cityCode == "") {
          this.addForm.city = res.data.rows[0].regionName;
          this.addForm.cityCode = res.data.rows[0].regionCode;
        }
  
        const res2 = await reqRegionLevel(this.addForm.cityCode);
        this.areaList = res2.data.rows;
        if (this.addForm.area == "") return; //地图中没获取到区级不走下面
        res2.data.rows.forEach((item) => {
          if (item.regionName == this.addForm.area) {
            this.addForm.areaCode = item.regionCode; //区行政码
            return;
          }
        });
  
        //   if (this.addForm.areaCode == "" || this.addForm.areaCode == null)
        //     return this.$modal.notifyWarning("数据异常，请联系管理员");
        const res3 = await reqRegionLevel(this.addForm.areaCode);
        this.streetList = res3.data.rows;
        if (this.addForm.street == "") return; //地图中没获取到街道不走下面
        res3.data.rows.forEach((item) => {
          if (item.regionName == this.addForm.street) {
            this.addForm.streetCode = item.regionCode; //街道行政码
            return;
          }
        });
        // console.log(this.addForm.streetCode);
  
        const res4 = await reqRegionLevel(this.addForm.streetCode);
        this.communityList = res4.data.rows;
        if (this.addForm.community == "") return;
        res4.data.rows.forEach((item) => {
          if (item.regionName == this.addForm.community) {
            this.addForm.communityCode = item.regionCode; //街道行政码
            return;
          }
        });
      },
      // 点击新增
      submit() {
        this.$refs.refForm.validate(async (valid) => {
          if (!valid) return;
          let {
            orgName,
            lat,
            lng,
            province,
            provinceCode,
            city,
            cityCode,
            area,
            areaCode,
            street,
            streetCode,
            community,
            communityCode,
            address,
            flatType,
            nature, // 组织性质
            category,
            homeCountry,
            grade,
            telephone,
            corporateName,
            corporateIdCard,
            username,
            mobile,
            construction,
            parentId,
            type,
          } = this.addForm;
          if (!streetCode) return this.$modal.notifyWarning("请选择地区");
          let params = {
            parentId,
            tenantId: this.user.tenantId,
            orgName,
            lat,
            lng,
            province,
            provinceCode,
            city,
            cityCode,
            area,
            areaCode,
            street,
            streetCode,
            community,
            communityCode,
            address,
            flatType,
            nature, // 组织性质
            category,
            homeCountry,
            grade,
            telephone,
            corporateName,
            corporateIdCard,
            username,
            mobile,
            construction,
            type,
          };
          const res = await reqOrgAdd(params);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("新增成功");
          this.closeDialog();
          this.$parent.getDataList();
        });
      },
      //地址转经纬度
      addrHand() {
        let that = this;
        // console.log(that.addForm.province+that.addForm.city+that.addForm.area+that.addForm.address);
        $.ajax({
          type: "get",
          dataType: "jsonp",
          data: {
            key: "44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53", // 填申请到的腾讯key
            address:
              that.addForm.province +
              that.addForm.city +
              that.addForm.area +
              that.addForm.street +
              that.addForm.address, //具体的地址
            output: "jsonp", //返回格式：支持JSON/JSONP，默认JSON
          },
          jsonp: "callback",
          jsonpCallback: "QQmap",
          url: "https://apis.map.qq.com/ws/geocoder/v1/?",
          success: function (json) {
            // console.log(json)
            if (json.status == 0) {
              that.addForm.lng = json.result.location.lng;
              that.addForm.lat = json.result.location.lat;
              // console.log(that.addForm.lat);
              // console.log(that.addForm.lng);
              // that.$message({
              //   message: '成功获取位置的经纬度',
              //   type: 'success'
              // })
            } else {
              // that.$message.error('获取该位置经纬度失败')
            }
          },
          error: function (err) {
            // that.$message.error('异常错误，请刷新浏览器后重试')
          },
        });
      },
      // 点击关闭弹框
      closeDialog() {
        this.dialogVisible = false;
        this.areaList = [];
        this.streetList = [];
        this.cityList = [];
        this.communityList = [];
        this.addForm = {
          orgName: "",
          flatType: "",
          username: "",
          lat: "",
          lng: "",
          province: "",
          provinceCode: "",
          city: "",
          cityCode: "",
          area: "",
          areaCode: "",
          street: "",
          streetCode: "",
          address: "",
          communityCode: "", //社区
          community: "",
          nature: "", // 组织性质
          category: "",
          homeCountry: "",
          grade: "",
          telephone: "",
          corporateName: "",
          corporateIdCard: "",
          mobile: "",
          construction: "",
          parentId: "",
          type: "4",
        };
        this.$nextTick(() => {
          this.$refs.refForm.resetFields();
          this.$refs.refForm.clearValidate();
          this.$refs.refTreeSearchAdd.resetFields();
        });
      },
      closeDialog2() {
        this.$nextTick(() => {
          this.$refs.refForm.resetFields();
        });
      },
    },
  
    deactivated() {
      if (this.$refs.refForm != null) {
        this.closeDialog();
      }
      this.innerVisible = false;
    },
  };
  </script>
  
  <style lang="less" scoped>
  @import url("../../../common.less");
  
  .mapLoc {
    // height: 100vh;
    // width: 100vw;
    // position: fixed;
    // z-index: 9999;
    // top: 0;
    // left: 0;
  
    height: 60vh;
    width: 100%;
    overflow-y: hidden;
  
    .iframe {
      width: 100%;
      height: 100%;
    }
  }
  
  .zuobiao {
    color: @primaryTxtcolor;
  }
  
  // ::v-deep .el-textarea__inner {
  //   color: #ececed !important;
  // }
  // 省市区/
  ::v-deep .el-input.is-disabled .el-input__inner {
    border-color: @primaryBorderColor !important;
  }
  
  // 折叠样式
  .el_collapse {
    color: @primaryThemeTxtColor2;
  }
  
  ::v-deep .el-collapse-item__header {
    // color: @primaryThemeTxtColor2;
    color: #7367f0 !important;
    width: 140px;
    height: 45px;
    line-height: 45px;
    font-size: 14px;
    // padding-left: 15px;
  }
  
  .el-collapse {
    border: none;
  }
  
  ::v-deep .el-collapse-item__arrow {
    margin: 0;
  }
  
  ::v-deep .el-collapse-item__content {
    padding-bottom: 0;
  }
  
  ::v-deep .el-collapse-item__wrap {
    background: transparent;
  }
  
  // 折叠样式结束
  .el-icon-question {
    margin-left: 10px;
    color: #7367f0;
    cursor: pointer;
    font-size: 20px;
  }
  </style>
  